﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents; 
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Runtime.Serialization;
using System.Windows.Browser;

namespace silvertweet
{
    public partial class MainPage : UserControl
    {
        private string clickURL;

        public MainPage()
        {
            InitializeComponent();
            WebClient web = new WebClient();
            web.DownloadStringCompleted += new DownloadStringCompletedEventHandler(web_DownloadStringCompleted);
            web.DownloadStringAsync(new Uri("http://www.messwithsilverlight.com/latesttweets.php"));
        }

        public MainPage(string twitterJSONUrl)
        {
            InitializeComponent();
            WebClient web = new WebClient();
            web.DownloadStringCompleted += new DownloadStringCompletedEventHandler(web_DownloadStringCompleted);
            web.DownloadStringAsync(new Uri(twitterJSONUrl));
        }
        
        public MainPage(string twitterJSONUrl, string hideHeader)
        {
            InitializeComponent();
            WebClient web = new WebClient();
            web.DownloadStringCompleted += new DownloadStringCompletedEventHandler(web_DownloadStringCompleted);
            web.DownloadStringAsync(new Uri(twitterJSONUrl));
            if (hideHeader == "false")
            {
                Header.Visibility = Visibility.Collapsed;
            }
        }

        void web_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            waitingOnImage.Visibility = Visibility.Collapsed;
            
            if (e.Error == null)
            {
                string raw = e.Result;
                JsonObject tweet = JsonObject.Parse(e.Result) as JsonObject;
                latestTweet.Text = (string)tweet["status"];
                twitterName.Text = string.Concat("@", (string)tweet["screen_name"]);
                this.clickURL = "http://www.twitter.com/" + (string)tweet["screen_name"] + "/status/" + (long)tweet["status_id"];
                twitterDate.Text = (string)tweet["created_at"];
                LayoutRoot.MouseLeftButtonUp += new MouseButtonEventHandler(LayoutRoot_MouseLeftButtonUp);
                LayoutRoot.Cursor = Cursors.Hand;
            }
            else
            {
                latestTweet.Text = "Oops. Something is weird. We can't get our latest tweet.";
            }
        }

        void LayoutRoot_MouseLeftButtonUp(Object sender, MouseButtonEventArgs e)
        {
            HtmlPage.Window.Navigate(new Uri(this.clickURL));
        }
    }
}
